package com.bkhc.common.repository;

import com.alibaba.fastjson.JSONObject;
import com.bkhc.common.entity.User;
import com.bkhc.common.util.response.ResultJson;
import com.fasterxml.jackson.databind.ObjectMapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.web.client.RestTemplate;
import java.util.List;
import java.util.Map;

@Component
public class UmcRepository {
    @Autowired
    private RestTemplate restTemplate;

    public List<User> getUserByUsername(String  username){
        String serviceName = "UMC-APP";
        String url = "http://" + serviceName + "/service/user/getUserByUsername?username="+username;
        ResultJson<List<User>>  result = restTemplate.postForObject(url, null, ResultJson.class);
        return result.getData();
    }

    public User findByUserId(String userId) {
        String serviceName = "UMC-APP";
        String url = "http://" + serviceName + "/umc/service/user/getUserByUserId?userId="+userId;
        ResultJson result = restTemplate.postForObject(url, null, ResultJson.class);
        Map map = (Map) result.getData();
        JSONObject json = new JSONObject(map);
        ObjectMapper mapper = new ObjectMapper();
        User u = mapper.convertValue(json,User.class);
        return u;
    }

    public User findByUsername(String username) {
        String serviceName = "UMC-APP";
        String url = "http://" + serviceName + "/umc/service/user/getUserByUserId?username="+username;
        ResultJson result = restTemplate.postForObject(url, null, ResultJson.class);
        Map map = (Map) result.getData();
        JSONObject json = new JSONObject(map);
        ObjectMapper mapper = new ObjectMapper();
        User u = mapper.convertValue(json,User.class);
        return u;
    }

    public User getCurrentUser(){
        String serviceName = "UMC-APP";
        String url = "http://" + serviceName + "/umc/service/user/getCurrentUser";
        ResultJson<User> result = restTemplate.postForObject(url,null, ResultJson.class);
        return result.getData();
    }


    public User sysUserToUmc(User user) {
        String serviceName = "UMC-APP";
        String url = "http://" + serviceName + "/umc/service/user/add";
        Map map = restTemplate.postForObject(url, user, Map.class);
        User u = new User();
        u.setUsername(map.get("username")+"");
        u.setUserId(map.get("userId")+"");
        u.setFullName(map.get("fullName")+"");
        u.setPhone(map.get("phone")+"");
        return u;
    }
}
